<template>
  <div class="container findPwd">
    <div class="list-box">
      <div class="top-text">找回密码</div>
      <el-steps :active="active" finish-status="success" align-center>
        <el-step title="填写账号"></el-step>
        <el-step title="身份验证"></el-step>
        <el-step title="设置新密码"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <div class="box" v-if="active == 0">
        <el-form ref="form" :model="form" :rules="rules" label-position="top">
          <el-form-item label="用户名" prop="userName">
            <common-input
              v-model="form.userName"
              placeholder="请输入"
            ></common-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <common-input
              v-model="form.phone"
              placeholder="请输入"
            ></common-input>
          </el-form-item>
          <el-form-item label="验证码" prop="verifyCode">
            <div class="flex-box">
              <common-input
                v-model="form.verifyCode"
                placeholder="请输入"
              ></common-input>
              <img :src="codeUrl" @click="getCode" class="code-img" />
            </div>
          </el-form-item>
          <div class="next-div">
            <el-button
              type="primary"
              @click="checkAcount"
              :loading="firstLoading"
              >下一步</el-button
            >
          </div>
        </el-form>
      </div>

      <div class="box" v-if="active == 1">
        <template
          v-if="
            (!canSms && !canEmail && !hasSecurity) ||
              (!canSms && !hasSecurity && canEmail && !form2.email) ||
              (!canEmail && !hasSecurity && canSms && !form2.phone)
          "
        >
          <div style="text-align: center">
            <div style="color: #f56c6c; padding-top: 40px">
              消息中心服务异常，无法找回密码，请联系管理员
            </div>
          </div>
        </template>

        <template v-else>
          <div class="mode-div">
            <div
              v-if="canSms"
              :class="verifyType == '1' ? 'active' : 'no-active'"
              @click="verifyChange('1')"
            >
              手机验证
            </div>
            <div
              v-if="form2.email && canEmail"
              :class="verifyType == '2' ? 'active' : 'no-active'"
              @click="verifyChange('3')"
            >
              邮箱验证
            </div>
            <div
              v-if="hasSecurity"
              :class="verifyType == '4' ? 'active' : 'no-active'"
              @click="verifyChange('4', 'security')"
            >
              密保问题验证
            </div>
          </div>
          <!-- 验证手机号或者邮箱 -->
          <template v-if="!security">
            <div class="get-box">
              <div class="info-1">
                用户名<span>{{ form.userName }}</span>
              </div>
              <div class="input-box m-t-10">
                <div class="info-1" v-if="verifyType == '1'">
                  手机号<span>{{ form2.encodePhone }}</span>
                </div>
                <div class="info-1" v-if="verifyType == '2'">
                  邮箱<span>{{ form2.encodeEmail }}</span>
                </div>
                <div class="btn2">
                  <div class="item" v-if="!phoneYzm" @click="sendCode">
                    获取验证码
                  </div>
                  <div class="item" v-else>
                    重新获取（{{ phoneYzmTimes }}s）
                  </div>
                </div>
              </div>
              <el-form
                class="m-t-15"
                ref="checkForm"
                :model="checkForm"
                :rules="rulesCheckForm"
                label-position="left"
              >
                <el-form-item label="验证码" prop="msgVerCode">
                  <common-input
                    class="sms-input"
                    v-model="checkForm.msgVerCode"
                    placeholder="请输入"
                  ></common-input>
                </el-form-item>
              </el-form>
            </div>
            <div class="next-div">
              <!--              <el-button type="primary" @click="previous">上一步</el-button>-->
              <el-button
                type="primary"
                @click="checkCode"
                :loading="secondLoading"
                >下一步</el-button
              >
            </div>
          </template>
          <!-- 验证密保问题 -->
          <template v-else-if="security">
            <el-form
              ref="securityForm"
              key="securityForm"
              :model="securityForm"
              :rules="rulesSecurityForm"
              label-position="right"
            >
              <el-form-item label="问题1">
                <common-input
                  v-model="securityForm.firstQuestion"
                  placeholder="请输入"
                  readonly
                ></common-input>
              </el-form-item>
              <el-form-item label="答案" prop="answer1">
                <common-input
                  v-model="securityForm.answer1"
                  placeholder="请输入"
                ></common-input>
              </el-form-item>
              <el-form-item label="问题2">
                <common-input
                  v-model="securityForm.secondQuestion"
                  placeholder="请输入"
                  readonly
                ></common-input>
              </el-form-item>
              <el-form-item label="答案" prop="answer2">
                <common-input
                  v-model="securityForm.answer2"
                  placeholder="请输入"
                ></common-input>
              </el-form-item>
              <el-form-item label="问题3">
                <common-input
                  v-model="securityForm.thirdQuestion"
                  placeholder="请输入"
                  readonly
                ></common-input>
              </el-form-item>
              <el-form-item label="答案" prop="answer3">
                <common-input
                  v-model="securityForm.answer3"
                  placeholder="请输入"
                ></common-input>
              </el-form-item>
            </el-form>
            <div class="next-div">
              <!--              <el-button type="primary" @click="previous">上一步</el-button>-->
              <el-button
                type="primary"
                @click="checkSecurity"
                :loading="thirdLoading"
                >下一步</el-button
              >
            </div>
          </template>
        </template>
      </div>

      <div class="box" v-if="active == 2">
        <el-form
          ref="form3"
          key="form3"
          :model="form3"
          :rules="rules3"
          label-position="top"
        >
          <el-form-item label="新密码" prop="newPwd">
            <common-input
              v-model="form3.newPwd"
              :verify="false"
              type="password"
              placeholder="请输入"
            ></common-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPwd">
            <common-input
              v-model="form3.confirmPwd"
              :verify="false"
              type="password"
              placeholder="请输入"
            ></common-input>
          </el-form-item>
          <div style="color: #999; font-size: 12px; line-height: 18px  ">
            <span v-if="row.minLength && row.maxLength">
              长度范围{{
                row.minLength || row.maxLength
                  ? `[${row.minLength}-${row.maxLength}]`
                  : "不限制"
              }} </span
            ><br />
            <span v-if="row.firstIsUpper || row.firstIsUpper == 0">
              首字母大写{{
                row.firstIsUpper || row.firstIsUpper == 0
                  ? firstIsUpper[row.firstIsUpper]
                  : "无"
              }} </span
            ><br />
            <span v-if="row.hasLower || row.hasLower == 0">
              小写字母{{
                row.hasLower || row.hasLower == 0
                  ? showTextRule[row.hasLower]
                  : "无"
              }} </span
            ><br />
            <span v-if="row.hasNumber || row.hasNumber == 0">
              数字{{
                row.hasNumber || row.hasNumber == 0
                  ? showTextRule[row.hasNumber]
                  : "无"
              }} </span
            ><br />
            <span v-if="row.hasSpecial || row.hasSpecial == 0">
              特殊字符{{
                row.hasSpecial || row.hasSpecial == 0
                  ? `${showTextRule[row.hasSpecial] + row.characters}`
                  : "无"
              }} </span
            ><br />
            <span v-if="row.hasUpper || row.hasUpper == 0">
              大写字母{{
                row.hasUpper || row.hasUpper == 0
                  ? showTextRule[row.hasUpper]
                  : "无"
              }}
            </span>
          </div>
          <div class="next-div m-t-40">
            <!--            <el-button type="primary" @click="previous">上一步</el-button>-->
            <el-button type="primary" @click="update" :loading="forLoading"
              >下一步</el-button
            >
          </div>
        </el-form>
      </div>

      <div class="box" v-if="active == 3">
        <div class="succ-div">
          <img class="succ-img" src="@/assets/images/succ.png" />
        </div>
        <div class="succ-title">成功设置新密码</div>
        <div class="succ-hint">请妥善保管密码</div>

        <div class="next-div m-t-40">
          <el-button type="danger" @click="complete">返回登录</el-button>
        </div>
      </div>
    </div>
    <div class="close" @click="$router.back(-1)">
      <i class="el-icon-close"></i>
    </div>
  </div>
</template>

<script>
var timeFlag = null;
import {
  getCodeImg,
  queryUser,
  querySecurityByUserName,
  sendVerCode,
  checkVerCode,
  passwordActionRetrievePassword,
  getMessageSceneBySceneCode,
  updatePwd,
  getUserPwdRule
} from "@/api/login";
import Utils from "@/utils";
import { deepClone } from "@/utils";
import { decode, encode } from "@/utils/aesUtils";
import { getDeFaultPwdRule } from "@/api/person/index";

export default {
  name: "",
  components: {},
  props: {},
  data() {
    const equalToPassword1 = (rule, value, callback) => {
      var regex = new RegExp(this.passRule.regex);
      if (!regex.test(value)) {
        callback(new Error("密码设置规则有误"));
        return false;
      } else {
        callback();
      }
    };
    const equalToPassword = (rule, value, callback) => {
      var regex = new RegExp(this.passRule.regex);
      if (this.form3.newPwd !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
        // if (!regex.test(value)) {
        //   callback(new Error("密码设置规则有误"));
        //   return false;
        // } else {
        //   callback();
        // }
      }
    };
    return {
      firstLoading: false,
      secondLoading: false,
      thirdLoading: false,
      forLoading: false,
      showTextRule: ["必须包含", "不允许包含", "不限制"],
      firstIsUpper: ["必须包含", "无", "不限制"],
      verifyType: "1",
      canSms: null,
      canEmail: null,
      //校验用户是否存在
      form: {
        phone: "",
        phonenumber: "",
        userName: "",
        verifyCode: "",
        verifyCodeUuid: ""
      },
      //发送短信验证码
      form2: {
        userName: "",
        email: "",
        phone: "",
        sendMsgType: "1" //1手机 3邮箱
      },
      checkForm: {
        msgVerCodeId: "",
        msgVerCode: "",
        userName: "",
        securityCode: "",
        businessName: "find_pwd"
      },
      //验证密保问题
      securityForm: {
        securityCode: "",
        answer1: "",
        answer2: "",
        answer3: ""
      },
      //设置密码
      form3: {
        confirmPwd: "",
        newPwd: "",
        securityCode: "",
        userName: ""
      },
      rules: {
        userName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          }
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur"
          }
        ],
        verifyCode: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur"
          }
        ]
      },
      rulesCheckForm: {
        msgVerCode: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur"
          }
        ]
      },
      rulesSecurityForm: {
        answer1: [
          {
            required: true,
            message: "请输入答案",
            trigger: "blur"
          }
        ],
        answer2: [
          {
            required: true,
            message: "请输入答案",
            trigger: "blur"
          }
        ],
        answer3: [
          {
            required: true,
            message: "请输入答案",
            trigger: "blur"
          }
        ]
      },
      rules3: {
        newPwd: [
          {
            required: true,
            message: "请输入新密码",
            trigger: "blur"
          }
          // {
          //   required: true,
          //   validator: equalToPassword1,
          //   trigger: "blur",
          // },
        ],
        confirmPwd: [
          {
            required: true,
            message: "请输入确认密码",
            trigger: "blur"
          },
          {
            required: true,
            validator: equalToPassword,
            trigger: "blur"
          }
        ]
      },
      passRule: {
        regex: "",
        regexDesc: ""
      },
      active: 0,
      codeUrl: "",
      row: [],
      phoneYzm: false, //旧手机验证码发送没
      phoneYzmTimes: 60,
      hasSecurity: false, //是否存在密保问题
      security: false, //是否是密保问题
      isCode: false
    };
  },

  // 方法
  methods: {
    getDeFaultPwdRule() {
      getUserPwdRule().then(res => {
        if (res && res.code === 200) {
          this.row = res.data;
        } else {
        }
      });
    },
    /**
     * 下一步
     */
    next() {
      if (this.active++ > 3) this.active = 0;
      this.phoneYzm = false;
    },

    /**
     * 上一步
     */
    previous() {
      if (this.active-- < 0) this.active = 0;
      this.getCode();
    },
    /**
     * 完成
     */
    complete() {
      this.$router.push("/login");
    },
    verifyChange(sendMsgType, type) {
      if (type) {
        //密保问题验证
        this.security = true;
        this.verifyType = "4";
      } else {
        this.security = false;
        this.form2.sendMsgType = sendMsgType;
        if (sendMsgType == "3") {
          this.verifyType = "2";
        } else {
          this.verifyType = "1";
        }
      }
    },
    /**
     * 验证身份验证码
     */
    getYzm() {},
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.form.verifyCodeUuid = res.uuid;
      });
    },
    /**
     * 验证当前用户是否存在
     */
    checkAcount() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.firstLoading = true;
          this.queryUser()
            .then(res => {
              if (res && res.code === 200) {
                this.getDeFaultPwdRule();
                this.form2.userName = this.form.userName;
                // this.form2.email = res.data.email;
                this.form2.phone = this.form.phonenumber
                  ? this.form.phonenumber
                  : "";
                this.form2.encodePhone = Utils.phoneEncryption(
                  decode(this.form2.phone)
                );
                this.form2.email = res.data.email ? res.data.email : "";
                this.form2.encodeEmail = Utils.emailEncryption(
                  decode(this.form2.email)
                );

                this.checkForm.userName = this.form.userName; //验证使用
                this.checkForm.securityCode = res.data.securityCode; //验证使用
                this.securityForm.securityCode = res.data.securityCode; //验证密保使用
                this.form3.userName = this.form.userName; //设置密码用
                Promise.all([
                  this.querySecurityByUserName(),
                  this.getMessageSceneBySceneCode()
                ]).then(res => {
                  if (
                    res[0].data.firstQuestion &&
                    res[0].data.firstQuestion.dictLabel
                  ) {
                    this.hasSecurity = true;
                    this.securityForm.firstQuestion =
                      res[0].data.firstQuestion.dictLabel;
                    this.securityForm.secondQuestion =
                      res[0].data.secondQuestion.dictLabel;
                    this.securityForm.thirdQuestion =
                      res[0].data.thirdQuestion.dictLabel;
                  } else {
                    this.hasSecurity = false;
                  }
                  this.canSms = res[1].data.sms === 0;
                  this.canEmail = res[1].data.email === 0;
                  if (res[1].data.sms === 0) {
                    this.verifyType = "1";
                    this.form2.sendMsgType = "1";
                    this.security = false;
                  } else if (res[1].data.email === 0 && this.form2.email) {
                    this.verifyType = "2";
                    this.form2.sendMsgType = "3";
                    this.security = false;
                  } else if (this.hasSecurity) {
                    this.verifyType = "4";
                    this.security = true;
                  }
                  this.next();
                  if (timeFlag) clearInterval(timeFlag);
                  this.phoneYzmTimes = 60;
                });
              } else {
                this.getCode();
                this.$GlobalErrorConfirm("操作失败", res.msg).then();
              }
            })
            .finally(() => (this.firstLoading = false));
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    /**
     * 获取当前用户手机号、邮箱、密保问题
     */
    queryUser() {
      return new Promise((resolve, reject) => {
        this.form.phonenumber = encode(this.form.phone);
        let params = Object.assign({}, this.form);
        delete params.phone;
        queryUser(params).then(res => {
          resolve(res);
        });
      });
    },

    /**
     * 获取密保问题
     */
    querySecurityByUserName() {
      return new Promise((resolve, reject) => {
        querySecurityByUserName({ userName: this.form.userName }).then(res => {
          if (res && res.code === 200) {
            resolve(res);
          } else {
            reject(res);
          }
        });
      });
    },

    /**
     * 获取消息服务中心信息
     */
    //getMessageSceneBySceneCode
    getMessageSceneBySceneCode() {
      return new Promise((resolve, reject) => {
        const params = {
          messageSceneCode: "SCENE_SYSTEM_FIND_PWD"
        };
        getMessageSceneBySceneCode(params).then(res => {
          if (res && res.code === 200) {
            resolve(res);
          } else {
            reject(res);
          }
        });
      });
    },

    //发送短信验证码
    sendCode() {
      // this.next();
      let params = deepClone(this.form2);
      delete params.encodeEmail;
      delete params.encodePhone;
      if (!this.isCode) {
        this.isCode = true;
        sendVerCode(params)
          .then(res => {
            if (res && res.code === 200) {
              this.phoneYzm = true;
              this.checkForm.msgVerCodeId = res.data.msgVerCodeId;
              timeFlag = setInterval(() => {
                this.phoneYzmTimes--;
                if (this.phoneYzmTimes === 0) {
                  this.phoneYzm = false;
                  this.phoneYzmTimes = 60;
                  // this.checkForm.msgVerCodeId = '';
                  clearInterval(timeFlag);
                }
              }, 1000);
            } else {
              this.$GlobalErrorConfirm("操作失败", res.msg).then();
            }
          })
          .finally(() => (this.isCode = false));
      }
    },
    //校验验证码
    checkCode() {
      this.$refs["checkForm"].validate(valid => {
        if (valid) {
          this.secondLoading = true;
          checkVerCode(this.checkForm)
            .then(res => {
              if (res && res.code === 200) {
                this.passRule.regex = res.data.regex;
                this.passRule.regexDesc = res.data.regexDesc;
                this.form3.securityCode = res.data.securityCode; //设置密码用
                this.next();
              } else {
                this.$GlobalErrorConfirm("操作失败", res.msg).then();
              }
            })
            .finally(() => (this.secondLoading = false));
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    /**
     * 校验密保答案
     */
    checkSecurity() {
      this.$refs["securityForm"].validate(valid => {
        if (valid) {
          let answers =
            encode(this.securityForm.answer1) +
            "," +
            encode(this.securityForm.answer2) +
            "," +
            encode(this.securityForm.answer3);
          this.thirdLoading = true;
          passwordActionRetrievePassword({
            answers: answers,
            securityCode: this.securityForm.securityCode,
            userName: this.form.userName
          })
            .then(res => {
              if (res && res.code === 200) {
                this.passRule.regex = res.data.regex;
                this.passRule.regexDesc = res.data.regexDesc;
                this.form3.securityCode = res.data.securityCode; //设置密码用
                this.next();
              } else {
                this.$GlobalErrorConfirm("操作失败", res.msg).then();
              }
            })
            .finally(() => (this.thirdLoading = false));
        } else {
          return false;
        }
      });
    },
    //重置密码
    update() {
      this.$refs["form3"].validate(valid => {
        if (valid) {
          let params = Object.assign({}, this.form3, {
            confirmPwd: encode(this.form3.confirmPwd),
            newPwd: encode(this.form3.newPwd)
          });
          this.forLoading = true;
          updatePwd(params)
            .then(res => {
              if (res && res.code === 200) {
                this.next();
              } else {
                this.$GlobalErrorConfirm("操作失败", res.msg).then();
              }
            })
            .finally(() => (this.forLoading = false));
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getCode();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {}
};
</script>
<style lang="scss">
.findPwd {
  .close {
    position: fixed;
    right: 0;
    top: 0;
    z-index: 2;
    padding: 10px;
    color: #000;
    cursor: pointer;

    .el-icon-close {
      color: #909399;
      font-size: 16px;
    }

    /*&:hover {*/
    /*  span {*/
    /*    transform: rotate(180deg);*/
    /*  }*/
    /*}*/
  }

  .list-box {
    width: 85%;
    margin: 20px auto 30px;
    clear: both;
    height: auto;
    overflow: hidden;
    padding: 20px;
    background: #ffffff;
    border-radius: 4px;

    .top-text {
      text-align: center;
      font-size: 20px;
      margin-bottom: 20px;
      padding-bottom: 20px;
      border-bottom: solid 1px #eee;
    }

    .box {
      width: 400px;
      margin: 60px auto;

      .info-1 {
        padding: 16px 0 16px 0;
        font-size: 14px;

        span {
          font-size: 15px;
        }
      }

      .get-box {
        clear: both;

        .input-box {
          display: flex;
          align-items: center;

          .btn2 {
            cursor: pointer;
            margin-left: 10px;
            padding: 0 10px;
            margin-left: 20px;
            text-align: center;
            border: #1890ff solid 1px;
            border-radius: 2px;
            font-size: 14px;
            color: #1890ff;
            height: 35px;
            line-height: 35px;
          }

          .sms-lable {
            width: 80px;
          }
        }
      }

      .el-form-item__label {
        padding-bottom: 0 !important;
      }

      .el-input--medium .el-input__inner {
        height: 44px;
        line-height: 44px;
        font-size: 15px;
      }

      .code-img {
        width: 100%;
        text-align: center;
        height: 44px;
        width: 140px;
        margin-left: 20px;

        img {
          width: 100%;
          display: block;
        }
      }

      .flex-box {
        display: flex;
      }

      .notice {
        font-size: 13px;
        color: #999;
        padding-top: 8px;
      }

      .m-t-10 {
        margin-top: 10px;
      }

      .m-t-15 {
        margin-top: 18px;
      }

      .m-t-30 {
        margin-top: 30px;
      }

      .m-t-40 {
        margin-top: 40px;
      }

      .next-div {
        display: flex;
        margin-top: 40px;
        width: 100%;
        text-align: center;

        .el-button {
          flex: 1;
        }
      }

      .success {
        line-height: 200px;
        text-align: center;
        font-size: 15px;
      }

      .mode-div {
        width: 100%;
        height: 50px;
        font-size: 16px;
        border-bottom: solid 1px #eee;
        margin-bottom: 20px;

        .active {
          cursor: pointer;
          // width: 110px;
          padding: 0 20px;
          height: 50px;
          line-height: 50px;
          float: left;
          color: #0d69b1;
          border-bottom: solid 1px #0d69b1;
        }

        .no-active {
          cursor: pointer;
          // width: 110px;
          padding: 0 20px;
          height: 50px;
          line-height: 50px;
          float: left;
          color: #666;
          border-bottom: solid 1px #eee;
        }
      }

      .succ-div {
        width: 100%;
        height: 100px;
        text-align: center;

        .succ-img {
          width: 80px;
          height: 80px;
        }
      }

      .succ-title {
        text-align: center;
        font-size: 24px;
      }

      .succ-hint {
        text-align: center;
        font-size: 14px;
        color: #666;
        margin-top: 6px;
      }
    }
  }
}
</style>
